export default class my_vue_router {

    constructor(props) {
        const { routes } = props
        this.routes = routes
        const history = new History()
        history.listen(() => {
            this.vm.$forceUpdate()
        })
    }

    static install(Vue) {
        Vue.mixin({
            created() {
                if (this.$options.router) {
                    this.$options.router.vm = this
                }
            },
        })

        Vue.component('router-view', {
            functional: true,
            render(createElement, { parent }) {
                const router = parent.$options.router
                const routes = router.routes
                const currentComp = getCurrentComp(routes)
                return createElement(currentComp)
            }
        })

        Vue.component('router-link', {
            render(createElement) {
                return createElement("a")
            }
        }, this.$slot)
    }
}

const getCurrentComp = (routes) => {
    const currentHash = window.location.hash
    const currnetRoute = routes.find(item => item.path === currentHash.replace(/^#/, ""))
    return currnetRoute.component
}

class History {
    listen = (callback) => {
        window.addEventListener('hashchange', () => {
            callback && callback()
        })
    }
    push = path => {
        window.history.pushState('#/' + path)
    }
}